package cn.dinkevin.xui.util;

import android.annotation.SuppressLint;
import android.util.Log;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间处理辅助工具类
 * @author chengpengfei
 */
@SuppressLint("SimpleDateFormat")
public class TimeUtil {

	private TimeUtil(){}
	
	/**
	 * 标准的时间格式：yyyy-MM-dd HH:mm:ss
	 */
	public static final SimpleDateFormat FORMAT_STANDARD = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 时间戳 格式：yyyyMMddHHmmsss
	 */
	public static final SimpleDateFormat FORMAT_STAMP = new SimpleDateFormat("yyyyMMddHHmmss");
	
	/**
	 * 日期格式 格式：yyyy-MM-dd
	 */
	public static final SimpleDateFormat FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
	
	/**
	 * 日期格式 格式：MM-dd
	 */
	public static final SimpleDateFormat FORMAT_Md = new SimpleDateFormat("MM-dd");
	
	/**
	 * 日期格式 格式：MM-dd HH:mm
	 */
	public static final SimpleDateFormat FORMAT_MdHm = new SimpleDateFormat("MM-dd HH:mm");

	/**
	 * 时间格式 格式：HH:mm
	 */
	public static final SimpleDateFormat FORMAT_MMDDHHMM = new SimpleDateFormat("MM月dd日 HH:mm");

	/**
	 * 时间格式 格式：MM月dd日 MM:dd
	 */
	public static final SimpleDateFormat FORMAT_Hm = new SimpleDateFormat("MM月dd日");

	/**
	 * 时间格式 格式：HH时mm分 HH:mm
	 */
	public static final SimpleDateFormat FORMAT_HHmm = new SimpleDateFormat("HH:mm");

	/**
	 * 时间格式 格式: yyyy年MM月dd日
	 */
	public static final SimpleDateFormat FORMAT_yMd = new SimpleDateFormat("yyyy年MM月dd日");

	/**
	 * 时间格式 格式：yyyy/MM/dd
	 */
	public static final SimpleDateFormat FORMAT_yMd_1 = new SimpleDateFormat("yyyy/MM/dd");

	/**
	 * 获取当前时间
	 * @param dateFormat 指定时间格式
	 * @return
     */
	public static String getCurrentTime(SimpleDateFormat dateFormat){
		Date date = new Date();
		return dateFormat.format(date);
	}

	/**
	 * 格式化时间
	 * @param time
	 * @param dateFormat
	 * @return
	 */
	public static String formatTime(long time, SimpleDateFormat dateFormat){
		Date date = new Date();
		date.setTime(time);
		return dateFormat.format(date);
	}

	private static String[] g_dayInWeek = new String[]{"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
	public static String getDayInWeek(){
		int index;
		Calendar calendar = Calendar.getInstance();
		index = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		return g_dayInWeek[index];
	}

	/**
	 * 时间转换
	 * @param timestamp
	 * @return
     */
	public static Date parseToDate(long timestamp){
		Date date = new Date();
		date.setTime(timestamp);
		return date;
	}

	/**
	 * 格式化时间到指定的格式
	 * @param timeString
	 * @param format
     * @return
     */
	public static String format(String timeString,SimpleDateFormat format){
		Date date = null;
		try{
			date = FORMAT_STANDARD.parse(timeString);
		}catch (ParseException e){
			LogUtil.e(timeString,"try parse failed",FORMAT_STANDARD.toPattern());
		}

		if(null == date){
			try{
				date = FORMAT_DATE.parse(timeString);
			}catch (ParseException e){
				LogUtil.e(timeString,"try parse failed",FORMAT_DATE.toPattern());
			}
		}

		if(null == date){
			try{
				date = FORMAT_STAMP.parse(timeString);
			}catch (ParseException e){
				LogUtil.e(timeString,"try parse failed",FORMAT_STAMP.toPattern());
			}
		}

		if(null == date){
			try{
				date = FORMAT_yMd.parse(timeString);
			}catch (ParseException e){
				LogUtil.e(timeString,"try parse failed",FORMAT_yMd.toPattern());
			}
		}

		if(null == date){
			try{
				date = FORMAT_yMd_1.parse(timeString);
			}catch (ParseException e){
				LogUtil.e(timeString,"try parse failed",FORMAT_yMd_1.toPattern());
			}
		}

		if(null == date){
			try{
				SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.s");
				date = f.parse(timeString);
			}catch (ParseException e){
				LogUtil.e(timeString,"try parse failed",FORMAT_yMd_1.toPattern());
			}
		}
		if(null == date) return "";

		return format.format(date);
	}
	
	/**
	 * 格式到社区时间方式显示
	 * @param time
	 * @return
	 */
	public static String formatToCommunityTime(long time){
		Date now = new Date();
		Calendar calNow = Calendar.getInstance();
		int dayNow = calNow.get(Calendar.DAY_OF_YEAR);
		
		Calendar calTime = Calendar.getInstance();
		calTime.setTimeInMillis(time);
		int dayTime = calTime.get(Calendar.DAY_OF_YEAR);
		
		long diff = now.getTime() - time;
		// 时间容错处理，阀值为10秒
		if(diff < 0){
			diff = Math.abs(diff);
			if(diff > 10000){
				return "时间转换错误：传入参数比现在还以后呢？";
			}
		}
		long minute = diff / (1000 * 60);
		if(minute == 0) return "刚刚";
		if(minute < 60) return minute + "分钟前";
		
		long hour = minute / 60;
		if(Math.abs(dayNow - dayTime) == 1 && hour > 10) return "昨天";
		if(hour < 24)
		{
			return hour + "小时前";
		}
		
		long day = hour / 24;
		
		if(Math.abs(dayNow - dayTime) == day + 1)
			day++;
		return day + "天前";
	}

	/**
	 * 计算两个时间间相差的天数（end - start 的天数）
	 * @return
     */
	public static int calculateNumbersOfDay(long start,long end){
		int dayNumber = (int) ((end - start) / (1000 * 60 * 60 * 24));
		return dayNumber;
	}

	/**
	 * 格式化动态时间格式
	 * @param time
	 * @return
	 */
	public static String formatToStatusTime(long time){
		if(time < 0) return "传入参数不正确";

		Date now = new Date();
		Calendar calNow = Calendar.getInstance();
		int dayNow = calNow.get(Calendar.DAY_OF_YEAR);

		Calendar calTime = Calendar.getInstance();
		calTime.setTimeInMillis(time);
		int dayTime = calTime.get(Calendar.DAY_OF_YEAR);

		long diff = now.getTime() - time;
		// 时间容错处理，阀值为10秒
		if(diff < 0){
			diff = Math.abs(diff);
			if(diff > 10000){
				LogUtil.e("时间转换错误：传入参数比现在还以后呢？");
				return "刚刚";
			}
		}
		long minute = diff / (1000 * 60);
		if(minute == 0) return "刚刚";
		if(minute < 60) return minute + "分钟前";

		long hour = minute / 60;
		if(Math.abs(dayNow - dayTime) == 1 && hour > 10) return "昨天";
		if(hour < 24){
			return hour + "小时前";
		}

		Calendar fromCalendar = Calendar.getInstance();
		fromCalendar.setTime(calTime.getTime());
		fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
		fromCalendar.set(Calendar.MINUTE, 0);
		fromCalendar.set(Calendar.SECOND, 0);
		fromCalendar.set(Calendar.MILLISECOND, 0);

		Calendar toCalendar = Calendar.getInstance();
		toCalendar.setTime(calNow.getTime());
		toCalendar.set(Calendar.HOUR_OF_DAY, 0);
		toCalendar.set(Calendar.MINUTE, 0);
		toCalendar.set(Calendar.SECOND, 0);
		toCalendar.set(Calendar.MILLISECOND, 0);

		int dayNumber = (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
		return dayNumber + "天前";
	}

	/**
	 * 格式化动态时间格式
	 * @return
	 */
	public static String formatToStatusTime2(String str){
		long time = parseToDate(str,FORMAT_STANDARD).getTime();
		if(time < 0) return "传入参数不正确";

		Date now = new Date();
		Calendar calNow = Calendar.getInstance();
		int dayNow = calNow.get(Calendar.DAY_OF_YEAR);

		Calendar calTime = Calendar.getInstance();
		calTime.setTimeInMillis(time);
		int dayTime = calTime.get(Calendar.DAY_OF_YEAR);

		long diff = now.getTime() - time;
		// 时间容错处理，阀值为10秒
		if(diff < 0){
			diff = Math.abs(diff);
			if(diff > 1000*10){
				LogUtil.e("时间转换错误：传入参数比现在还以后呢？");
				return "刚刚";
			}
		}
		long minute = diff / (1000 * 60);
		if(diff<1000*60) return "刚刚";
		if(minute < 60) return minute + "分钟前";
		long hour = minute / 60;

        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(calTime.getTime());
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(calNow.getTime());
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        int dayNumber = (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
        if (dayNumber>365){
           //非今年 2016年12月22号
			 	return 	format(str,FORMAT_yMd);
        }else {
            //今年
            if(hour < 24){
                if (Math.abs(dayNow-dayTime)==1){
                    //昨天 7月31号
				return 	format(str,FORMAT_Hm);
                }else {
                    //今天 05:20
					return 	format(str,FORMAT_HHmm);
                }
            }else {
                // 7月31号
				return format(str,FORMAT_Hm) ;
            }
        }
	}

	/**
	 * 格式化新闻时间格式
	 * @param time
	 * @return
	 */
	public static String formatToNewsTime(long time){
		if(time < 0) return "传入参数不正确";
		
		Date now = new Date();
		Calendar calNow = Calendar.getInstance();
		int dayNow = calNow.get(Calendar.DAY_OF_YEAR);
		
		Calendar calTime = Calendar.getInstance();
		calTime.setTimeInMillis(time);
		int dayTime = calTime.get(Calendar.DAY_OF_YEAR);
		
		long diff = now.getTime() - time;
		// 时间容错处理，阀值为10秒
		if(diff < 0){
			diff = Math.abs(diff);
			if(diff > 10000){
				LogUtil.e("时间转换错误：传入参数比现在还以后呢？");
				return "刚刚";
			}
		}
		long minute = diff / (1000 * 60);
		if(minute == 0) return "刚刚";
		if(minute < 60) return minute + "分钟前";
		
		long hour = minute / 60;
		if(Math.abs(dayNow - dayTime) == 1 && hour > 10) return "昨天";
		if(hour < 24){
			return hour + "小时前";
		}
		
		int month = calTime.get(Calendar.MONTH) + 1;
		int day = calTime.get(Calendar.DAY_OF_MONTH);
		
		return ((month < 10) ? "0" + month: Integer.toString(month)) + "-" + (day < 10 ? "0" + day: Integer.toString(day));
	}
	
	/**
	 * 将字符串格式时间转化到毫秒格式
	 * @param time
	 * @return
	 */
	public static long getTime(String time){
		try {
			return FORMAT_STANDARD.parse(time).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return -1;
	}


	/**
	 * 将字符串格式时间转化到毫秒格式
	 * @param format
	 * @param time
	 * @return
	 */
	public static long getTime(DateFormat format, String time){
		try {
			return format.parse(time).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return -1;
	}


	public static String getCurrentTime(){
		return FORMAT_STANDARD.format(new Date());
	}
	
	/**
	 * 获取当前日期 格式为 yyyy-MM-dd
	 * @return
	 */
	public static String getCurrentDateString(){
		return FORMAT_DATE.format(new Date());
	}

	public static String getCurrentDateyyyyMMddHHmmssString(){
		return FORMAT_STANDARD.format(new Date());
	}

	/**
	 * 当前日期
	 * @return
     */
	public static Date getCurrentDate(){
		return new Date(System.currentTimeMillis());
	}
	
	/**
	 * 获取唯一标识时间戳
	 * @return 例如：2017070512253536
	 */
	public static String getCurrentTimeStamp(){
		return FORMAT_STAMP.format(new Date());
	}
	
	/**
	 * 转化到日期
	 * @param dateString
	 * @return
	 */
	public static Date parseToDate(String dateString){
		try {
			return FORMAT_DATE.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 时间字符串转换到时间
	 * @param date 时间字符串
	 * @param format 时间格式
     * @return 时间对象
     */
	public static Date parseToDate(String date,SimpleDateFormat format){
		if(StringUtil.isEmpty(date)) return new Date();
		ParsePosition position = new ParsePosition(0);
		return format.parse(date,position);
	}
	
	/**
	 * 日期对比
	 * @param start
	 * @param end
	 * @return 1 -> start 晚于 end;0 -> start 与 end 日期相同;-1 -> start 早于 end
	 */
	public static int dateCompare(Date start, Date end){
		Calendar calStart = Calendar.getInstance();
		calStart.set(start.getYear(),start.getMonth(),start.getDate());
		
		Calendar calEnd = Calendar.getInstance();
		calEnd.set(end.getYear(),end.getMonth(),end.getDate());
		return calStart.compareTo(calEnd);
	}

	/**
	 * 格式化通知时间 date类型
	 * @param time
	 * @return
     */
	public static  Date getNoticeDateTime(String time){
		Date date=null;
		try {
			 date=FORMAT_STANDARD.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 将时间格式转换到时间戳
	 * @param time
	 * @return
	 */
	public static String convertToTimestamp(String time){
		if(StringUtil.isEmpty(time)) return null;
		String result = time.replaceAll("-","").replaceAll(" ","").replaceAll(":","").replaceAll("_","");
		return result;
	}

	/**
	 * 获取格式化通知时间 String
	 * @return
	 */
	public static String getNoticeTime(Date date){
		return FORMAT_MMDDHHMM.format(date);
	}

	/**
	 * 比较两个日期相差的天数
	 * @param maxDateStr 较大的日期（格式 yyyy-MM-dd）
	 * @param minDateStr 较小的日期（格式 yyyy-MM-dd）
	 * @return
	 */
	public static int daysOfTwo(String maxDateStr, String minDateStr) {
		int difference = 0;
		try {
			Date maxDate = FORMAT_DATE.parse(maxDateStr);
			Date minDate = FORMAT_DATE.parse(minDateStr);
			difference = (int) ((maxDate.getTime() - minDate.getTime()) / (1000*3600*24));
		} catch (ParseException e) {
			e.printStackTrace();
		}finally {
			return difference;
		}

	}

	/**
	 *  获取当前日期是星期几
	 * @param strDate  2018-04-25
	 * @return
	 */
	public static String getWeekByDateStr(String strDate)
	{
		int year = Integer.parseInt(strDate.substring(0, 4));
		int month = Integer.parseInt(strDate.substring(5, 7));
		int day = Integer.parseInt(strDate.substring(8, 10));

		Calendar c = Calendar.getInstance();

		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month - 1);
		c.set(Calendar.DAY_OF_MONTH, day);

		String week = "";
		int weekIndex = c.get(Calendar.DAY_OF_WEEK);

		switch (weekIndex)
		{
			case 1:
				week = "星期日";
				break;
			case 2:
				week = "星期一";
				break;
			case 3:
				week = "星期二";
				break;
			case 4:
				week = "星期三";
				break;
			case 5:
				week = "星期四";
				break;
			case 6:
				week = "星期五";
				break;
			case 7:
				week = "星期六";
				break;
		}
		return week;
	}
}
